<template>
  <div class="home">
    <img class="centered-button" src="@/assets/eye.jpg" @click="startSpeechRecognition">

    <!-- 语音输入弹窗 -->
    <el-dialog title="语音搜索" :visible.sync="showVoiceInput" @close="stopSpeechRecognition" class="voice-dialog" center>
      <div class="voice-input-dialog">
        <el-icon class="voice-icon" name="el-icon-microphone"></el-icon>
        <div class="voice-text">{{ voiceInputStatus }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showVoiceInput: false, // 控制语音输入弹窗显示
      voiceInputStatus: '' // 语音输入状态信息
    };
  },
  methods: {
    startSpeechRecognition() {
      navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
          const audioContext = new (window.AudioContext || window.webkitAudioContext)();
          const source = audioContext.createMediaStreamSource(stream);
          const analyser = audioContext.createAnalyser();
          source.connect(analyser);
          analyser.fftSize = 256;
          const dataArray = new Uint8Array(analyser.frequencyBinCount);
          this.showVoiceInput = true;
          this.stream = stream;
          this.intervalId = setInterval(() => {
            analyser.getByteFrequencyData(dataArray);
            const average = dataArray.reduce((acc, cur) => acc + cur, 0) / dataArray.length;
            this.voiceInputStatus = average > 0 ? '当前正在进行语音输入...' : '未检测到声音，请大声一点';
          }, 1000);
          setTimeout(() => {
            this.voiceInputStatus = '语音转文字内容：我想要穿衣服';
            setTimeout(() => {
              this.stopSpeechRecognition();
            }, 2000);
          }, 3000);
        })
        .catch(error => {
          console.error('获取麦克风权限失败:', error);
        });
    },
    stopSpeechRecognition() {
      this.showVoiceInput = false;
      this.voiceInputStatus = '';
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null;
      }
      if (this.$route.path !== '/about') {
        this.$router.push('/about');
      }
    }
  }
};
</script>

<style scoped>
.voice-dialog {
  max-width: 90%;
  margin: 0;
  padding: 10px;
}

.voice-input-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-icon {
  font-size: 48px;
  color: #409EFF;
}

.voice-text {
  margin-left: 20px;
  font-size: 18px;
}

.home {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.centered-button {
  width: 300px;
  height: 300px;
}

@media (max-width: 768px) {
  .voice-dialog {
    max-width: 95%;
  }
}
</style>
